import React, { useState } from 'react';
import { Card, Form, Input, Button, Table, Tag, Timeline, Empty } from 'antd';
import { SearchOutlined, LinkOutlined, CheckCircleOutlined } from '@ant-design/icons';
import './styles.css';

// 模拟存证记录数据
const mockTracingRecord = {
  hashCode: '0x7b2274797065223a227472616e73616374696f6e5f70726f6f66222c226964223a22545832303234303331383031227d',
  transactionInfo: {
    id: 'TX2024031801',
    orderNo: 'ORDER2024031801',
    transactionType: 'data_exchange',
    amount: 5000,
    createTime: '2024-03-18 10:00:00',
    status: 'completed',
    dataProvider: {
      name: '数据提供方A',
      id: 'DP2024001',
      license: 'L2024001A',
    },
    dataConsumer: {
      name: '数据使用方B',
      id: 'DC2024001',
      license: 'L2024001B',
    },
    dataAsset: {
      name: '个人信息数据集',
      id: 'DA2024001',
      type: 'structured_data',
      size: '1.5GB',
      format: 'CSV',
    },
    authorization: {
      scope: ['read', 'analyze'],
      validFrom: '2024-03-18 10:00:00',
      validTo: '2024-04-18 10:00:00',
      restrictions: ['no_export', 'no_storage'],
    }
  },
  records: [
    {
      id: 1,
      timestamp: '2024-03-18 10:00:00',
      operation: 'transaction_initiation',
      operator: '数据使用方B',
      description: '发起数据交易请求',
      blockHeight: 12345678,
      transactionHash: '0x8a7b2274797065223a227472616e73616374696f6e5f696e6974696174696f6e222c226964223a22545832303234303331383031227d',
    },
    {
      id: 2,
      timestamp: '2024-03-18 10:02:00',
      operation: 'authorization_check',
      operator: '系统',
      description: '验证交易双方资质',
      blockHeight: 12345679,
      transactionHash: '0x9b7b2274797065223a22617574686f72697a6174696f6e5f636865636b222c226964223a22545832303234303331383031227d',
    },
    {
      id: 3,
      timestamp: '2024-03-18 10:05:00',
      operation: 'contract_signing',
      operator: '数据提供方A',
      description: '签署数据使用合同',
      blockHeight: 12345680,
      transactionHash: '0xa7b2274797065223a22636f6e74726163745f7369676e696e67222c226964223a22545832303234303331383031227d',
    },
    {
      id: 4,
      timestamp: '2024-03-18 10:08:00',
      operation: 'payment_confirmation',
      operator: '数据使用方B',
      description: '支付交易费用',
      blockHeight: 12345681,
      transactionHash: '0xb7b2274797065223a227061796d656e745f636f6e6669726d6174696f6e222c226964223a22545832303234303331383031227d',
    },
    {
      id: 5,
      timestamp: '2024-03-18 10:10:00',
      operation: 'data_preparation',
      operator: '数据提供方A',
      description: '准备数据资源',
      blockHeight: 12345682,
      transactionHash: '0xc7b2274797065223a22646174615f707265706172696e67222c226964223a22545832303234303331383031227d',
    },
    {
      id: 6,
      timestamp: '2024-03-18 10:15:00',
      operation: 'data_transfer',
      operator: '系统',
      description: '数据安全传输',
      blockHeight: 12345683,
      transactionHash: '0xd7b2274797065223a22646174615f7472616e73666572222c226964223a22545832303234303331383031227d',
    },
    {
      id: 7,
      timestamp: '2024-03-18 10:20:00',
      operation: 'transaction_completion',
      operator: '系统',
      description: '交易完成确认',
      blockHeight: 12345684,
      transactionHash: '0xe7b2274797065223a227472616e73616374696f6e5f636f6d706c6574696f6e222c226964223a22545832303234303331383031227d',
    },
  ],
};

const DataTracing: React.FC = () => {
  const [searchForm] = Form.useForm();
  const [tracingData, setTracingData] = useState<any>(null);

  const handleSearch = (values: any) => {
    console.log('Search values:', values);
    // 模拟API调用
    setTracingData(mockTracingRecord);
  };

  const columns = [
    {
      title: '时间戳',
      dataIndex: 'timestamp',
      key: 'timestamp',
    },
    {
      title: '操作类型',
      dataIndex: 'operation',
      key: 'operation',
      render: (operation: string) => {
        const operationMap = {
          transaction_initiation: { color: 'blue', text: '交易发起' },
          authorization_check: { color: 'cyan', text: '资质验证' },
          contract_signing: { color: 'purple', text: '合同签署' },
          payment_confirmation: { color: 'gold', text: '支付确认' },
          data_preparation: { color: 'magenta', text: '数据准备' },
          data_transfer: { color: 'orange', text: '数据传输' },
          transaction_completion: { color: 'green', text: '交易完成' }
        };
        const { color, text } = operationMap[operation as keyof typeof operationMap] || 
          { color: 'default', text: operation };
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作方',
      dataIndex: 'operator',
      key: 'operator',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
    },
    {
      title: '区块高度',
      dataIndex: 'blockHeight',
      key: 'blockHeight',
    },
    {
      title: '交易哈希',
      dataIndex: 'transactionHash',
      key: 'transactionHash',
      render: (hash: string) => (
        <a href={`https://explorer.example.com/tx/${hash}`} target="_blank" rel="noopener noreferrer">
          {hash.substring(0, 10)}...{hash.substring(hash.length - 8)}
        </a>
      ),
    },
  ];

  return (
    <div className="data-tracing">
      <Card title="数据溯源">
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          className="search-form"
        >
          <Form.Item
            name="hashCode"
            label="存证HashCode"
            rules={[{ required: true, message: '请输入存证HashCode' }]}
          >
            <Input
              placeholder="请输入存证HashCode"
              style={{ width: 400 }}
              prefix={<LinkOutlined />}
            />
          </Form.Item>
          <Form.Item>
            <Button type="primary" icon={<SearchOutlined />} htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>

        {tracingData ? (
          <>
            <Card
              type="inner"
              title="存证信息"
              className="tracing-info"
              extra={
                <Tag icon={<CheckCircleOutlined />} color="success">
                  已验证
                </Tag>
              }
            >
              <div className="tracing-info-content">
                <div className="info-section">
                  <h4>基本信息</h4>
                  <p><strong>存证HashCode：</strong>{tracingData.hashCode}</p>
                  <p><strong>交易编号：</strong>{tracingData.transactionInfo.id}</p>
                  <p><strong>订单编号：</strong>{tracingData.transactionInfo.orderNo}</p>
                  <p><strong>交易类型：</strong>{tracingData.transactionInfo.transactionType === 'data_exchange' ? '数据交换' : '数据服务'}</p>
                  <p><strong>交易金额：</strong>￥{tracingData.transactionInfo.amount.toLocaleString()}</p>
                  <p><strong>创建时间：</strong>{tracingData.transactionInfo.createTime}</p>
                  <p><strong>交易状态：</strong><Tag color="success">已完成</Tag></p>
                </div>
                
                <div className="info-section">
                  <h4>参与方信息</h4>
                  <div className="participant-info">
                    <div>
                      <h5>数据提供方</h5>
                      <p><strong>名称：</strong>{tracingData.transactionInfo.dataProvider.name}</p>
                      <p><strong>ID：</strong>{tracingData.transactionInfo.dataProvider.id}</p>
                      <p><strong>许可证：</strong>{tracingData.transactionInfo.dataProvider.license}</p>
                    </div>
                    <div>
                      <h5>数据使用方</h5>
                      <p><strong>名称：</strong>{tracingData.transactionInfo.dataConsumer.name}</p>
                      <p><strong>ID：</strong>{tracingData.transactionInfo.dataConsumer.id}</p>
                      <p><strong>许可证：</strong>{tracingData.transactionInfo.dataConsumer.license}</p>
                    </div>
                  </div>
                </div>

                <div className="info-section">
                  <h4>数据资产信息</h4>
                  <p><strong>资产名称：</strong>{tracingData.transactionInfo.dataAsset.name}</p>
                  <p><strong>资产ID：</strong>{tracingData.transactionInfo.dataAsset.id}</p>
                  <p><strong>数据类型：</strong>{tracingData.transactionInfo.dataAsset.type}</p>
                  <p><strong>数据大小：</strong>{tracingData.transactionInfo.dataAsset.size}</p>
                  <p><strong>数据格式：</strong>{tracingData.transactionInfo.dataAsset.format}</p>
                </div>

                <div className="info-section">
                  <h4>授权信息</h4>
                  <p><strong>授权范围：</strong>{tracingData.transactionInfo.authorization.scope.join(', ')}</p>
                  <p><strong>有效期：</strong>{tracingData.transactionInfo.authorization.validFrom} 至 {tracingData.transactionInfo.authorization.validTo}</p>
                  <p><strong>使用限制：</strong>{tracingData.transactionInfo.authorization.restrictions.join(', ')}</p>
                </div>
              </div>
            </Card>

            <Card type="inner" title="溯源记录" className="tracing-timeline">
              <Timeline mode="left">
                {tracingData.records.map((record: any) => {
                  let color = 'blue';
                  switch (record.operation) {
                    case 'transaction_initiation':
                      color = 'blue';
                      break;
                    case 'authorization_check':
                      color = 'cyan';
                      break;
                    case 'contract_signing':
                      color = 'purple';
                      break;
                    case 'payment_confirmation':
                      color = 'gold';
                      break;
                    case 'data_preparation':
                      color = 'magenta';
                      break;
                    case 'data_transfer':
                      color = 'orange';
                      break;
                    case 'transaction_completion':
                      color = 'green';
                      break;
                    default:
                      color = 'blue';
                  }
                  
                  return (
                    <Timeline.Item
                      key={record.id}
                      label={record.timestamp}
                      color={color}
                    >
                      <p>
                        <strong>{record.operator}</strong> - {record.description}
                      </p>
                      <p className="timeline-hash">
                        交易哈希：
                        <a
                          href={`https://explorer.example.com/tx/${record.transactionHash}`}
                          target="_blank"
                          rel="noopener noreferrer"
                        >
                          {record.transactionHash.substring(0, 10)}...
                          {record.transactionHash.substring(record.transactionHash.length - 8)}
                        </a>
                      </p>
                    </Timeline.Item>
                  );
                })}
              </Timeline>
            </Card>

            <Card type="inner" title="详细记录">
              <Table columns={columns} dataSource={tracingData.records} rowKey="id" />
            </Card>
          </>
        ) : (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description="请输入存证HashCode进行查询"
          />
        )}
      </Card>
    </div>
  );
};

export default DataTracing; 